<?php


/**
 * ECSHOP 公用函数库
 * ============================================================================
 * 版权所有 (C) 2005-2007 康盛创想（北京）科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改和再发布。
 * ============================================================================
 * $Author: wj $
 * $Date: 2007-11-02 16:57:36 +0800 (星期五, 02 十一月 2007) $
 * $Id: lib_common.php 13413 2007-11-02 08:57:36Z wj $
*/

if (!defined('IN_WONDERSHARE'))
{
    die('Hacking attempt');
}

/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */
function sub_str($str, $length = 0, $append = true)
{
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength)
    {
        return $str;
    }
    elseif ($length < 0)
    {
        $length = $strlength + $length;
        if ($length < 0)
        {
            $length = $strlength;
        }
    }

    if (function_exists('mb_substr'))
    {
        $newstr = mb_substr($str, 0, $length, 'UTF-8');
    }
    elseif (function_exists('iconv_substr'))
    {
        $newstr = iconv_substr($str, 0, $length, 'UTF-8');
    }
    else
    {
        $newstr = trim_right(substr($str, 0, $length));
    }

    if ($append && $str != $newstr)
    {
        $newstr .= '...';
    }

    return $newstr;
}

/**
 * 去除字符串右侧可能出现的乱码
 *
 * @param   string      $str        字符串
 *
 * @return  string
 */
function trim_right($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]+/', '', $str)) % 3;

    if ($length > 0)
    {
        $str = substr($str, 0, 0 - $length);
    }

    return $str;
}

/**
 * 计算字符串的长度（汉字按照两个字符计算）
 *
 * @param   string      $str        字符串
 *
 * @return  int
 */
function str_len($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

    if ($length)
    {
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else
    {
        return strlen($str);
    }
}

/**
 * 获得用户操作系统的换行符
 *
 * @access  public
 * @return  string
 */
function get_crlf()
{
/* LF (Line Feed, 0x0A, \N) 和 CR(Carriage Return, 0x0D, \R) */
    if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win'))
    {
        $the_crlf = '\r\n';
    }
    elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac'))
    {
        $the_crlf = '\r'; // for old MAC OS
    }
    else
    {
        $the_crlf = '\n';
    }

    return $the_crlf;
}

/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 * @author   Xuan Yan
 *
 * @return   void
 */
function db_create_in($item_list, $field_name = '',$toInt = false)
{
    if (empty($item_list))
    {
        return $field_name . " IN ('') ";
    }
    else
    {
        if (!is_array($item_list))
        {
            $item_list = explode(',', $item_list);
        }
        $item_list = array_unique($item_list);
        $item_list_tmp = '';

        foreach ($item_list AS $item)
        {
        	if ($item !== '')
            {
            	if($toInt){
            	   $item_list_tmp .= $item_list_tmp ? ",$item" : "$item";
            	}else{
                   $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
            	}
            }
        }
        if (empty($item_list_tmp))
        {
            return $field_name . " IN ('') ";
        }
        else
        {
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }
    }
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

/**
 * 验证输入的邮件地址是否合法
 *
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 *
 * @return bool
 */
function is_email($user_email)
{
        $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
        if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
     {
        if (preg_match($chars, $user_email))
        {
            return true;
        } else
        {
            return false;
        }
    } else
        {
            return false;
        }
}

/**
 * 检查是否为一个合法的时间格式
 *
 * @access  public
 * @param   string  $time
 * @return  void
 */
function is_time($time)
{
    $pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';

    return preg_match($pattern, $time);
}

/**
 * 获得查询时间和次数，并赋值给smarty
 *
 * @access  public
 * @return  void
 */
function assign_query_info()
{
    if ($GLOBALS['db']->queryTime == '')
    {
        $query_time = 0;
    }
    else
    {
        if (PHP_VERSION >= '5.0.0')
        {
            $query_time = number_format(microtime(true) - $GLOBALS['db']->queryTime, 6);
        }
        else
        {
            list($now_usec, $now_sec)     = explode(' ', microtime());
            list($start_usec, $start_sec) = explode(' ', $GLOBALS['db']->queryTime);
            $query_time = number_format(($now_sec - $start_sec) + ($now_usec - $start_usec), 6);
        }
    }
    $GLOBALS['smarty']->assign('query_info', sprintf($GLOBALS['_LANG']['query_info'], $GLOBALS['db']->queryCount, $query_time));

    /* 内存占用情况 */
    if ($GLOBALS['_LANG']['memory_info'] && function_exists('memory_get_usage'))
    {
        $GLOBALS['smarty']->assign('memory_info', sprintf($GLOBALS['_LANG']['memory_info'], memory_get_usage() / 1048576));
    }

    /* 是否启用了 gzip */
    $gzip_enabled = gzip_enabled() ? $GLOBALS['_LANG']['gzip_enabled'] : $GLOBALS['_LANG']['gzip_disabled'];
    $GLOBALS['smarty']->assign('gzip_enabled', $gzip_enabled);
}


/**
 * 获得服务器上的 GD 版本
 *
 * @access      public
 * @return      int         可能的值为0，1，2
 */
function gd_version()
{
    include_once(ROOT_PATH . 'includes/cls_image.php');

    return cls_image::gd_version();
}

/**
 * 获得指定分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 * @return  string
 */
function get_children($cat = 0)
{
    return 'g.cat_id ' . db_create_in(array_unique(array_merge(array($cat), array_keys(cat_list($cat, 0, false)))));
}

/**
 * 获得指定文章分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 *
 * @return void
 */
function get_article_children ($cat = 0)
{
    return db_create_in(array_unique(array_merge(array($cat), array_keys(article_cat_list($cat, 0, false)))), 'cat_id');
}

/**
 * 邮件发送
 *
 * @param: $name[string]        接收人姓名
 * @param: $email[string]       接收人邮件地址
 * @param: $subject[string]     邮件标题
 * @param: $content[string]     邮件内容
 * @param: $type[int]           0 普通邮件， 1 HTML邮件
 * @param: $notification[bool]  true 要求回执， false 不用回执
 *
 * @return boolean
 */

function send_mail($name, $email, $subject, $content, $type = 0, $notification=false)
{
    /* 如果邮件编码不是utf8，创建字符集转换对象，转换编码 */
    if ($GLOBALS['_CFG']['mail_charset'] != 'UTF8')
    {
        $name      = ecs_iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $name);
        $subject   = ecs_iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $subject);
        $content   = ecs_iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $content);
        $GLOBALS['_CFG']['shop_name'] = ecs_iconv('UTF8', $GLOBALS['_CFG']['mail_charset'], $GLOBALS['_CFG']['shop_name']);
        $charset   = $GLOBALS['_CFG']['mail_charset'];
    }
    else
    {
        $charset = 'UTF-8';
    }

    /**
     * 使用mail函数发送邮件
     */
    if ($GLOBALS['_CFG']['mail_service'] == 0 && function_exists('mail'))
    {
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ?
            'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;


        $headers = array();
        $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['shop_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        $headers[] = $content_type . '; format=flowed';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['shop_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        }

        $res = @mail($email, '=?' . $charset . '?B?' . base64_encode($subject) . '?=', $content, implode("\r\n", $headers));

        if (!$res)
        {
            $GLOBALS['err'] ->add($GLOBALS['_LANG']['sendemail_false']);

            return false;
        }
        else
        {
            return true;
        }
    }
    /**
     * 使用smtp服务发送邮件
     */
    else
    {
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ?
            'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;
        $content   =  base64_encode($content);

        $headers = array();
        $headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
        $headers[] = 'To: "' . '=?' . $charset . '?B?' . base64_encode($name) . '?=' . '" <' . $email. '>';
        $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['shop_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        $headers[] = 'Subject: ' . '=?' . $charset . '?B?' . base64_encode($subject) . '?=';
        $headers[] = $content_type . '; format=flowed';
        $headers[] = 'Content-Transfer-Encoding: base64';
        $headers[] = 'Content-Disposition: inline';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($GLOBALS['_CFG']['shop_name']) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        }

        /* 获得邮件服务器的参数设置 */
        $params['host'] = $GLOBALS['_CFG']['smtp_host'];
        $params['port'] = $GLOBALS['_CFG']['smtp_port'];
        $params['user'] = $GLOBALS['_CFG']['smtp_user'];
        $params['pass'] = $GLOBALS['_CFG']['smtp_pass'];

        if (empty($params['host']) || empty($params['port']))
        {
            // 如果没有设置主机和端口直接返回 false
            $GLOBALS['err'] ->add($GLOBALS['_LANG']['smtp_setting_error']);

            return false;
        }
        else
        {
            // 发送邮件
            if (!function_exists('fsockopen'))
            {
                //如果fsockopen被禁用，直接返回
                $GLOBALS['err']->add($GLOBALS['_LANG']['disabled_fsockopen']);

                return false;
            }

            include_once(ROOT_PATH . 'includes/cls_smtp.php');
            static $smtp;

            $send_params['recipients'] = $email;
            $send_params['headers']    = $headers;
            $send_params['from']       = $GLOBALS['_CFG']['smtp_mail'];
            $send_params['body']       = $content;

            if (!isset($smtp))
            {
                $smtp = new smtp($params);
            }

            if ($smtp->connect() && $smtp->send($send_params))
            {
                return true;
            }
            else
            {
                $err_msg = $smtp->error_msg();
                if (empty($err_msg))
                {
                    $GLOBALS['err']->add('Unknown Error');
                }
                else
                {
                    if (strpos($err_msg, 'Failed to connect to server') !== false)
                    {
                        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['smtp_connect_failure'], $params['host'] . ':' . $params['port']));
                    }
                    else if (strpos($err_msg, 'AUTH command failed') !== false)
                    {
                        $GLOBALS['err']->add($GLOBALS['_LANG']['smtp_login_failure']);
                    }
                    elseif (strpos($err_msg, 'bad sequence of commands') !== false)
                    {
                        $GLOBALS['err']->add($GLOBALS['_LANG']['smtp_refuse']);
                    }
                    else
                    {
                        $GLOBALS['err']->add($err_msg);
                    }
                }

                return false;
            }
        }
    }
}

if (!function_exists('file_get_contents'))
{
    /**
     * 如果系统不存在file_get_contents函数则声明该函数
     *
     * @access  public
     * @param   string  $file
     * @return  mix
     */
    function file_get_contents($file)
    {
        if (($fp = @fopen($file, 'rb')) === false)
        {
            return false;
        }
        else
        {
            $fsize = @filesize($file);
            if ($fsize)
            {
                $contents = fread($fp, $fsize);
            }
            else
            {
                $contents = '';
            }
            fclose($fp);

            return $contents;
        }
    }
}

if (!function_exists('file_put_contents'))
{
    define('FILE_APPEND', 'FILE_APPEND');

    /**
     * 如果系统不存在file_put_contents函数则声明该函数
     *
     * @access  public
     * @param   string  $file
     * @param   mix     $data
     * @return  int
     */
    function file_put_contents($file, $data, $flags = '')
    {
        $contents = (is_array($data)) ? implode('', $data) : $data;

        if ($flags == 'FILE_APPEND')
        {
            $mode = 'ab+';
        }
        else
        {
            $mode = 'wb';
        }

        if (($fp = @fopen($file, $mode)) === false)
        {
            return false;
        }
        else
        {
            $bytes = fwrite($fp, $contents);
            fclose($fp);

            return $bytes;
        }
    }
}

if (!function_exists('floatval'))
{
    /**
     * 如果系统不存在 floatval 函数则声明该函数
     *
     * @access  public
     * @param   mix     $n
     * @return  float
     */
    function floatval($n)
    {
        return (float) $n;
    }
}

/**
 * 文件或目录权限检查函数
 *
 * @access          public
 * @param           string  $file_path   文件路径
 * @param           bool    $rename_prv  是否在检查修改权限时检查执行rename()函数的权限
 *
 * @return          int     返回值的取值范围为{0 <= x <= 15}，每个值表示的含义可由四位二进制数组合推出。
 *                          返回值在二进制计数法中，四位由高到低分别代表
 *                          可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。
 */
function file_mode_info($file_path)
{
    /* 如果不存在，则不可读、不可写、不可改 */
    if (!file_exists($file_path))
    {
        return false;
    }

    $mark = 0;

    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
    {
        /* 测试文件 */
        $test_file = $file_path . '/cf_test.txt';

        /* 如果是目录 */
        if (is_dir($file_path))
        {
            /* 检查目录是否可读 */
            $dir = @opendir($file_path);
            if ($dir === false)
            {
                return $mark; //如果目录打开失败，直接返回目录不可修改、不可写、不可读
            }
            if (@readdir($dir) !== false)
            {
                $mark ^= 1; //目录可读 001，目录不可读 000
            }
            @closedir($dir);

            /* 检查目录是否可写 */
            $fp = @fopen($test_file, 'wb');
            if ($fp === false)
            {
                return $mark; //如果目录中的文件创建失败，返回不可写。
            }
            if (@fwrite($fp, 'directory access testing.') !== false)
            {
                $mark ^= 2; //目录可写可读011，目录可写不可读 010
            }
            @fclose($fp);

            @unlink($test_file);

            /* 检查目录是否可修改 */
            $fp = @fopen($test_file, 'ab+');
            if ($fp === false)
            {
                return $mark;
            }
            if (@fwrite($fp, "modify test.\r\n") !== false)
            {
                $mark ^= 4;
            }
            @fclose($fp);

            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
            @unlink($test_file);
        }
        /* 如果是文件 */
        elseif (is_file($file_path))
        {
            /* 以读方式打开 */
            $fp = @fopen($file_path, 'rb');
            if ($fp)
            {
                $mark ^= 1; //可读 001
            }
            @fclose($fp);

            /* 试着修改文件 */
            $fp = @fopen($file_path, 'ab+');
            if ($fp && @fwrite($fp, '') !== false)
            {
                $mark ^= 6; //可修改可写可读 111，不可修改可写可读011...
            }
            @fclose($fp);

            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
        }
    }
    else
    {
        if (@is_readable($file_path))
        {
            $mark ^= 1;
        }

        if (@is_writable($file_path))
        {
            $mark ^= 14;
        }
    }

    return $mark;
}

function log_write($arg, $file = '', $line = '')
{
    if ((DEBUG_MODE & 4) != 4)
    {
        return;
    }

    $str = "\r\n-- ". date('Y-m-d H:i:s'). " --------------------------------------------------------------\r\n";
    $str .= "FILE: $file\r\nLINE: $line\r\n";

    if (is_array($arg))
    {
        $str .= '$arg = array(';
        foreach ($arg AS $val)
        {
            foreach ($val AS $key => $list)
            {
                $str .= "'$key' => '$list'\r\n";
            }
        }
        $str .= ")\r\n";
    }
    else
    {
        $str .= $arg;
    }

    file_put_contents(ROOT_PATH . 'data/log.txt', $str);
}

/**
 * 检查目标文件夹是否存在，如果不存在则自动创建该目录
 *
 * @access      public
 * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
 *
 * @return      bool
 */
function make_dir($folder)
{
    $reval = false;

    if (!file_exists($folder))
    {
        /* 如果目录不存在则尝试创建该目录 */
        @umask(0);

        /* 将目录路径拆分成数组 */
        preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);

        /* 如果第一个字符为/则当作物理路径处理 */
        $base = ($atmp[0][0] == '/') ? '/' : '';

        /* 遍历包含路径信息的数组 */
        foreach ($atmp[1] AS $val)
        {
            if ('' != $val)
            {
                $base .= $val;

                if ('..' == $val || '.' == $val)
                {
                    /* 如果目录为.或者..则直接补/继续下一个循环 */
                    $base .= '/';

                    continue;
                }
            }
            else
            {
                continue;
            }

            $base .= '/';

            if (!file_exists($base))
            {
                /* 尝试创建目录，如果创建失败则继续循环 */
                if (@mkdir($base, 0777))
                {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
        }
    }
    else
    {
        /* 路径已经存在。返回该路径是不是一个目录 */
        $reval = is_dir($folder);
    }

    clearstatcache();

    return $reval;
}

/**
 * 获得系统是否启用了 gzip
 *
 * @access  public
 *
 * @return  boolean
 */
function gzip_enabled()
{
    static $enabled_gzip = NULL;

    if ($enabled_gzip === NULL)
    {
        $enabled_gzip = ($GLOBALS['_CFG']['enable_gzip'] && function_exists('ob_gzhandler'));
    }

    return $enabled_gzip;
}

/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashes_deep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('addslashes_deep', $value) : daddslashes($value);
    }
}

/**
 * 将对象成员变量或者数组的特殊字符进行转义
 *
 * @access   public
 * @param    mix        $obj      对象或者数组
 * @author   Xuan Yan
 *
 * @return   mix                  对象或者数组
 */
function addslashes_deep_obj($obj)
{
    if (is_object($obj) == true)
    {
        foreach ($obj AS $key => $val)
        {
            $obj->$key = addslashes_deep($val);
        }
    }
    else
    {
        $obj = addslashes_deep($obj);
    }

    return $obj;
}

function daddslashes($string, $force = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}

/**
 * 递归方式的对变量中的特殊字符去除转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function stripslashes_deep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    }
}

/**
 *  清除指定后缀的模板缓存或编译文件
 *
 * @access  public
 * @param  bool       $is_cache  是否清除缓存还是清出编译文件
 * @param  string     $ext       需要删除的文件名，不包含后缀
 *
 * @return int        返回清除的文件个数
 */
function clear_tpl_files($is_cache = true, $ext = '')
{
    $dirs = array();

    if ($is_cache)
    {
        $dirs[] = ROOT_PATH . 'tmp/cache/';
    }
    else
    {
        $dirs[] = ROOT_PATH . 'tmp/templates_c/';
    }

    $str_len = strlen($ext);
    $count   = 0;

    foreach ($dirs AS $dir)
    {
        $folder = @opendir($dir);

        if ($folder == false)
        {
            continue;
        }

        while ($file = readdir($folder))
        {
            if ($file == '.' || $file == '..' || $file == 'index.htm' || $file == 'index.html')
            {
                continue;
            }
            if (is_file($dir . $file))
            {
                /* 如果有文件名则判断是否匹配 */
                $pos = ($is_cache) ? strrpos($file, '_') : strrpos($file, '.');

                if ($str_len > 0 && $pos !== false)
                {
                    $ext_str = substr($file, 0, $pos);

                    if ($ext_str == $ext)
                    {
                        if (@unlink($dir . $file))
                        {
                            $count++;
                        }
                    }
                }
                else
                {
                    if (@unlink($dir . $file))
                    {
                        $count++;
                    }
                }
            }
        }
        closedir($folder);
    }

    return $count;
}

/**
 * 清除模版编译文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_compiled_files($ext = null)
{
    return clear_tpl_files(false, $ext);
}

/**
 * 清除缓存文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_cache_files($ext = null)
{
    return clear_tpl_files(true, $ext);
}

/**
 * 清除模版编译和缓存文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名后缀
 * @return  void
 */
function clear_all_files($ext = null)
{
    return clear_tpl_files(false, $ext) + clear_tpl_files(true,  $ext);
}

/**
 * 页面上调用的js文件
 *
 * @access  public
 * @param   string      $files
 * @return  void
 */
function smarty_insert_scripts($args)
{
    static $scripts = array();

    $arr = explode(',', str_replace(' ','',$args['files']));

    $str = '';
    foreach ($arr AS $val)
    {
        if (in_array($val, $scripts) == false)
        {
            $scripts[] = $val;
            if ($val{0} == '.')
            {
                $str .= '<script type="text/javascript" src="' . $val . '"></script>';
            }
            else
            {
                $str .= '<script type="text/javascript" src="js/' . $val . '"></script>';
            }
        }
    }

    return $str;
}

/**
 * 创建分页的列表
 *
 * @access  public
 * @param   integer $count
 * @return  string
 */
function smarty_create_pages($params)
{
    extract($params);

    $str = '';
    $len = 10;

    if (empty($page))
    {
        $page = 1;
    }

    if (!empty($count))
    {
        $step = 1;
        $str .= "<option value='1'>1</option>";

        for ($i = 2; $i < $count; $i += $step)
        {
            $step = ($i >= $page + $len - 1 || $i <= $page - $len + 1) ? $len : 1;
            $str .= "<option value='$i'";
            $str .= $page == $i ? " selected='true'" : '';
            $str .= ">$i</option>";
        }

        if ($count > 1)
        {
            $str .= "<option value='$count'";
            $str .= $page == $count ? " selected='true'" : '';
            $str .= ">$count</option>";
        }
    }

    return $str;
}

/**
 * 格式化重量：小于1千克用克表示，否则用千克表示
 * @param   float   $weight     重量
 * @return  string  格式化后的重量
 */
function formated_weight($weight)
{
    $weight = round(floatval($weight), 3);
    if ($weight > 0)
    {
        if ($weight < 1)
        {
            /* 小于1千克，用克表示 */
            return intval($weight * 1000) . $GLOBALS['_LANG']['gram'];
        }
        else
        {
            /* 大于1千克，用千克表示 */
            return $weight . $GLOBALS['_LANG']['kilogram'];
        }
    }
    else
    {
        return 0;
    }
}

/**
 *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 *
 * @access  public
 * @param   string       $str         待转换字串
 *
 * @return  string       $str         处理后字串
 */
function make_semiangle($str)
{
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
                 '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
                 'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
                 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
                 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
                 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
                 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
                 'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
                 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
                 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
                 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
                 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
                 'ｙ' => 'y', 'ｚ' => 'z',
                 '（' => '(', '）' => ')', '［' => '[', '］' => ']', '【' => '[',
                 '】' => ']', '〖' => '[', '〗' => ']', '「' => '[', '」' => ']',
                 '『' => '[', '』' => ']', '｛' => '{', '｝' => '}', '《' => '<',
                 '》' => '>',
                 '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
                 '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
                 '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
                 '＂' => '"', '＇' => '`', '｀' => '`', '｜' => '|', '〃' => '"',
                 '　' => ' ');

    return strtr($str, $arr);
}

/**
 * 检查文件类型
 *
 * @access      public
 * @param       string      filename            文件名
 * @param       string      realname            真实文件名
 * @param       string      limit_ext_types     允许的文件类型
 * @return      string
 */
function check_file_type($filename, $realname = '', $limit_ext_types = '')
{
    if ($realname)
    {
        $extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
    }
    else
    {
        $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
    }

    $str = $format = '';

    $file = @fopen($filename, 'rb');
    if ($file)
    {
        $str = @fread($file, 0x400); // 读取前 1024 个字节
        @fclose($file);
    }
    else
    {
        if (stristr($filename, ROOT_PATH) === false)
        {
            if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
                $extname == 'xls' || $extname == 'txt'  || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
                $extname == 'pdf' || $extname == 'rm'   || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
                $extname == 'swf' || $extname == 'chm'  || $extname == 'sql' || $extname == 'cert')
            {
                $format = $extname;
            }
        }
        else
        {
            return '';
        }
    }

    if ($format == '' && strlen($str) >= 2 )
    {
        if (substr($str, 0, 4) == 'MThd' && $extname != 'txt')
        {
            $format = 'mid';
        }
        elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav')
        {
            $format = 'wav';
        }
        elseif (substr($str ,0, 3) == "\xFF\xD8\xFF")
        {
            $format = 'jpg';
        }
        elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt')
        {
            $format = 'gif';
        }
        elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
        {
            $format = 'png';
        }
        elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt')
        {
            $format = 'bmp';
        }
        elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt')
        {
            $format = 'swf';
        }
        elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0")
        {   // D0CF11E == DOCFILE == Microsoft Office Document
            if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc')
            {
                $format = 'doc';
            }
            elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls')
            {
                $format = 'xls';
            } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt')
            {
                $format = 'ppt';
            }
        } elseif (substr($str ,0, 4) == "PK\x03\x04")
        {
            $format = 'zip';
        } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt')
        {
            $format = 'rar';
        } elseif (substr($str ,0, 4) == "\x25PDF")
        {
            $format = 'pdf';
        } elseif (substr($str ,0, 3) == "\x30\0x82\0x0a")
        {
            $format = 'cert';
        } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt')
        {
            $format = 'chm';
        } elseif (substr($str ,0, 4) == "\x2ERMF")
        {
            $format = 'rm';
        } elseif ($extname == 'sql')
        {
            $format = 'sql';
        } elseif ($extname == 'txt')
        {
            $format = 'txt';
        }
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false)
    {
        $format = '';
    }

    return $format;
}

/**
 * 对 MYSQL LIKE 的内容进行转义
 *
 * @access      public
 * @param       string      string  内容
 * @return      string
 */
function mysql_like_quote($str)
{
    return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%'));
}

/**
 * 获取服务器的ip
 *
 * @access      public
 *
 * @return string
 **/
function real_server_ip()
{
    static $serverip = NULL;

    if ($serverip !== NULL)
    {
        return $serverip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['SERVER_ADDR']))
        {
            $serverip = $_SERVER['SERVER_ADDR'];
        }
        else
        {
            $serverip = '0.0.0.0';
        }
    }
    else
    {
        $serverip = getenv('SERVER_ADDR');
    }

    return $serverip;
}

/**
 * 自定义 header 函数，用于过滤可能出现的安全隐患
 *
 * @param   string  string  内容
 *
 * @return  void
 **/
function ecs_header($string, $replace = true, $http_response_code = 0)
{
    $string = str_replace(array("\r", "\n"), array('', ''), $string);

    if (preg_match('/^\s*location:/is', $string))
    {
        @header($string . "\n", $replace);

        exit();
    }

    if (empty($http_response_code) || PHP_VERSION < '4.3')
    {
        @header($string, $replace);
    }
    else
    {
        @header($string, $replace, $http_response_code);
    }
}

function ecs_iconv($source_lang, $target_lang, $source_string = '')
{
    static $chs = NULL;

    /* 如果字符串为空或者字符串不需要转换，直接返回 */
    if ($source_lang == $target_lang || $source_string == '' || preg_match("/[\x80-\xFF]+/", $source_string) == 0)
    {
        return $source_string;
    }

    if ($chs === NULL)
    {
        require_once(ROOT_PATH . 'includes/cls_iconv.php');
        $chs = new Chinese(ROOT_PATH);
    }

    return $chs->Convert($source_lang, $target_lang, $source_string);
}

function ecs_geoip($ip)
{
    static $fp = NULL, $offset = array(), $index = NULL;

    $ip    = gethostbyname($ip);
    $ipdot = explode('.', $ip);
    $ip    = pack('N', ip2long($ip));

    $ipdot[0] = (int)$ipdot[0];
    $ipdot[1] = (int)$ipdot[1];
    if ($ipdot[0] == 10 || $ipdot[0] == 127 || ($ipdot[0] == 192 && $ipdot[1] == 168) || ($ipdot[0] == 172 && ($ipdot[1] >= 16 && $ipdot[1] <= 31)))
    {
        return 'LAN';
    }

    if ($fp === NULL)
    {
        $fp     = fopen(ROOT_PATH . 'includes/codetable/ipdata.dat', 'rb');
        if ($fp === false)
        {
            return 'Invalid IP data file';
        }
        $offset = unpack('Nlen', fread($fp, 4));
        $index  = fread($fp, $offset['len'] - 4);
    }

    $length = $offset['len'] - 1028;
    $start  = unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
    for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8)
    {
        if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip)
        {
            $index_offset = unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
            $index_length = unpack('Clen', $index{$start + 7});
            break;
        }
    }

    fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
    $area = fread($fp, $index_length['len']);

    fclose($fp);
    $fp = NULL;

    return $area;
}

/**
 * 取得url内容
 */
function getBuffer($url)
{
	$handle=@fopen($url, "r");
	if(!$handle) die("error:".$url);
	$buf="";
	while(!feof($handle))
  	{
  		$buf .= fread($handle, 1024);
  	}
  	fclose($handle);
  	return $buf;
}

function writeLogger($msg,$func="")
{
	$data=array();
	$data['domain']=$_SERVER['SERVER_NAME'];
	$data['path']=$_SERVER['PHP_SELF'];
	$data['query']=empty($_SERVER['QUERY_STRING'])?"":"?".$_SERVER['QUERY_STRING'];
	$data['url']="http://".$data['domain'].$data['path'].$data['query'];
	$data['add_time']=time();
	$data['log']=addslashes($msg);
	$data['func']=$func;
	
	$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table("logger"),$data);
}

/**
 * 获得指定分类下的子分类的数组
 *
 * @access  public
 * @param   int     $cat_id     分类的ID
 * @param   int     $selected   当前选中分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
 * @param   int     $level      限定返回的级数。为0时返回所有级数
 * @param   int     $is_show_all 如果为true显示所有分类，如果为false隐藏不可见分类。
 * @param   string     $where    条件
 * @return  mix
 */
function cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0, $is_show_all = true,$where = ' WHERE c.cat_web = 1 AND c.cat_type = 1 ',$type = 0,$ar_vicecat_id= '')
{

    $res_c  = $res  = array();
    if (empty($res))
    {
//        $data = read_static_cache('cat_pid_releate');
//        if ($data === false)
//        { 
//            $str_c = '';
//            if($del_cat_id!=0)
//            {
//            	$str_c = " AND  c.cat_id != $del_cat_id ";
//            }
            $sql = "SELECT c.cat_id, c.cat_title, c.parent_id,  c.sort_order,c.cat_type,c.pub_time,c.pub_status
            ,c.template_url,c.cat_web,c.cat_id,c.add_user,c.update_time,c.add_time,c.parent_path,c.cat_related,c.cat_series, 
            c.is_recommended , COUNT(s.cat_id) AS has_children ".'FROM  category AS c '.
            "LEFT JOIN category  AS s ON s.parent_id=c.cat_id ".
            " $where AND c.is_delete = 0  GROUP BY c.cat_id ".
            ' ORDER BY  c.parent_id  ,c.sort_order  ASC';

            $res  = $GLOBALS['db']->getAll($sql);
     
            if($type == 0)
            {
              $sql = "SELECT cat_id FROM category WHERE cat_title = 'mobile'";
              $mobile_cat_id = $GLOBALS['db']->getOne($sql);
           
            }elseif($type == 1)
            {
            
             $date = array();
             $select = '';
             for($k = 0 ;$k<count($res);$k++)
             {
             	$date[$res[$k]['cat_title']] =  $res[$k];
             }
             ksort($date);
             foreach($date as $key=>$value)  
             {
              $str_array = explode(',',$value['parent_path']);
              if(count($str_array) == 2)
              {
              
              $select .= '<option value="' . $value['cat_id'] . '" ';
              $select .= ($selected == $value['cat_id']) ? "selected='ture'" : '';
              $select .= '>';
              $select .= htmlspecialchars(($value['cat_title']), ENT_QUOTES) . '</option>';
              }
             }
             return $select;
            }elseif ($type == 2)
            {
           
             $select = '';
             if(!empty($ar_vicecat_id))
             {
              $vicecat_arr = explode(',',$ar_vicecat_id);
    
              for($i = 0 ;$i<count($res);$i++)
              {
             
               $fage = 1;
               foreach ($vicecat_arr as $key=>$value)
               {
               	if($res[$i]['cat_id'] == $value )
               	{
               	  $fage = 0;
                  $select.='<input type="checkbox" name="cat-type[]" value='.$res[$i]['cat_id'].' checked="checked" />'.htmlspecialchars($res[$i]['cat_title']).' &nbsp;&nbsp;';
               	}
                
               }
               if($fage == 1)
               {
               	$select.='<input type="checkbox" name="cat-type[]" value='.$res[$i]['cat_id'].'  />'.htmlspecialchars($res[$i]['cat_title']).' &nbsp;&nbsp;';
               }
              }
             }else
             {               
               for($i = 0 ;$i<count($res);$i++)
               {
               
                 $select.='<input type="checkbox" name="cat-type[]" value='.$res[$i]['cat_id'].'  />'.htmlspecialchars($res[$i]['cat_title']).' &nbsp;&nbsp;';
               }
             }
    
             return $select;
            }
           
//            //如果数组过大，不采用静态缓存方式
//            if (count($res) <= 1000)
//            {
//                write_static_cache('cat_pid_releate', $res);
//            }
//        }
//        else
//        {
//            $res = $data;
//        }
    }

    if (empty($res) == true)
    {
        return $re_type ? '' : array();
    }

    $options = cat_options($cat_id, $res); // 获得指定分类下的子分类的数组
 
    foreach ($options AS $key => $value)
    {
 
      if($value['cat_id']!=0)
      {
//      $mobile_cat_id = empty($mobile_cat_id)?0:$mobile_cat_id;
      if(!empty($mobile_cat_id))
      {
       if(strstr($options[$cat_id]['parent_path'],$mobile_cat_id))
       {
       	$options[$cat_id]['is_c_mobile'] = 1;
       } 
      }else
      {
      	$options[$cat_id]['is_c_mobile'] = 0;
      }
       $cat_id = $value['cat_id'];
       $sql1 = " SELECT ar_id   FROM  `topic_article` WHERE FIND_IN_SET( '".$value['cat_id']."',  `ar_vicecat_id` ) AND ar_cat_id !='".$value['cat_id']."' AND is_delete = 0
			UNION SELECT ar_id  FROM  `topic_article` WHERE  `ar_cat_id` = '".$value['cat_id']."'  AND   is_delete = 0 ";    
       $query1 = $GLOBALS['db']->query($sql1);

       $options[$cat_id]['cat_count'] =  $GLOBALS['db']->num_rows($query1);
      
       $sql2 = "SELECT count(*) AS ws_count FROM won_product  WHERE cat_id =  '$cat_id' AND won_product_delete  = 0 ";
       $result = $GLOBALS['db']->query($sql2);
       $row = $GLOBALS['db']->fetch_array($result);
       $options[$cat_id]['ws_count'] = $row['ws_count'];
       $options[$cat_id]['update_time'] = !empty($value['update_time'])?local_date('Y-m-d H:i',$value['update_time']):'';
	   $options[$cat_id]['pub_time'] = !empty($value['pub_time'])?local_date('Y-m-d H:i',$value['pub_time']):'';
       $options[$cat_id]['add_time'] = !empty($value['add_time'])? local_date('Y-m-d H:i',$value['add_time']):'';
      }
      
    }
  

    if ($re_type == true)
    {
       $select = '';
       foreach ($options AS $var)
       {
       	  
          $select .= '<option value="' . $var['cat_id'] . '" ';
          $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
          $select .= '>';
          
          if ($var['level'] > 0){
                $select .= str_repeat('&nbsp;', $var['level'] * 2);
          }
          $select .= htmlspecialchars(($var['cat_title'])) . '</option>';
       }


        return $select;
    }
    else
    {

        return $options;
    }
}
/**
 * 过滤和排序所有分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */

function cat_options($spec_cat_id, $arr)
{
    static $cat_options = array();

    if (isset($cat_options[$spec_cat_id]))
    {
        return $cat_options[$spec_cat_id];
    }

    if (!isset($cat_options[0]))
    {
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();
//        $data = read_static_cache('cat_option_static');
//        if ($data === false)
//        {
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $cat_id = $value['cat_id'];
                    if ($level == 0 && $last_cat_id == 0)
                    {
                        if ($value['parent_id'] > 0)
                        {
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = htmlspecialchars($value['cat_title']);
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['parent_id'] == $last_cat_id)
                    {
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = htmlspecialchars($value['cat_title']);
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                }
            }
//            //如果数组过大，不采用静态缓存方式
//            if (count($options) <= 2000)
//            {
//                write_static_cache('cat_option_static', $options);
//            }
//        }
//        else
//        {
//            $options = $data;
//        }
        $cat_options[0] = $options;
    }
    else
    {
        $options = $cat_options[0];
    }

    if (!$spec_cat_id)
    {
        return $options;
    }
    else
    {
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }

        $spec_cat_id_level = $options[$spec_cat_id]['level'];

        foreach ($options AS $key => $value)
        {
            if ($key != $spec_cat_id)
            {
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }

        $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {
                $spec_cat_id_array[$key] = $value;
            }
        }
        $cat_options[$spec_cat_id] = $spec_cat_id_array;

        return $spec_cat_id_array;
    }
}


/**
 * 读结果缓存文件
 *
 * @params  string  $cache_name
 *
 * @return  array   $data
 */
function read_static_cache($cache_name)
{
    if ((DEBUG_MODE & 2) == 2)
    {
        return false;
    }
    static $result = array();
    if (!empty($result[$cache_name]))
    {
        return $result[$cache_name];
    }
    $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
    if (file_exists($cache_file_path))
    {
        include_once($cache_file_path);
        $result[$cache_name] = $data;
        return $result[$cache_name];
    }
    else
    {
        return false;
    }
}

/**
 * 写结果缓存文件
 *
 * @params  string  $cache_name
 * @params  string  $caches
 *
 * @return
 */
function write_static_cache($cache_name, $caches)
{
    if ((DEBUG_MODE & 2) == 2)
    {
        return false;
    }
    $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
    $content = "<?php\r\n";
    $content .= "\$data = " . var_export($caches, true) . ";\r\n";
    $content .= "?>";
    file_put_contents($cache_file_path, $content, LOCK_EX);
}

function get_page_no($pgnm,$pgno)
{
	$q = $_SERVER['QUERY_STRING'];
	parse_str($q,$qs);
	if($pgnm)
	{
	$qs[$pgnm] = $pgno;
	}
	return http_build_query($qs);
}

function get_explode($str,$delimiter)
{
	$arr = array();
	$arr = explode($delimiter,$str);
	return $arr[0];
}

/**************************************
	 * 获取价格
	 * @param array $product_info   当前产品数组
	 * @return array
	 **************************************/

function get_price($product_id)
{
	    global $db;
	   	$product_id=intval($product_id);
	   	$sql="SELECT * FROM license WHERE `product_id`=".$product_id;
	   	$prices = $db->getAll($sql);
	   	$prices = is_array($prices) ? $prices : array();
	   	$price = array();
	   	foreach($prices as $item){
	   		
	   		if($item['license_id'] == 11){
	   			if($item['sub_license_id'] == 0 )
	   			{
	   				if($item['website_display'])
	   				{
	   					$price['curr'] = $item['price'];
	   				}
	   				else 
	   				{
	   					$price['old'] = $item['price'];
	   					$price['unique'] = true;
	   				}
	   			}
	   			else
	   			{
	   				if($item['website_display'])
	   				{
	   					$price['curr'] = $item['price'];
	   				}
	   			}
	   		}
	   	}
	   	if(empty($price['curr'])){
	   		$price['curr'] = $price['old'];
	   		$price['unique'] = true;
	   	}
	   	return $price;
}
/**
 * 获得分页行导
 *
 * @access  public
 * @param   int     $page     页码
 * @param   int     $page_num 总页数
 * @return  string
 */
function get_page_url($page,$page_num,$where_s = '')
{
   	 $i = $page - 5;
	 if ($i < 1) {
			$i = 1;
	 }
	 $j = $i + 9;		
	 if ($j > $page_num) {
			$j = $page_num;
	 }
	 $str = '';
	
	 $str .= ($page == 1) ? '' : '<a href="?'.get_explode(get_page_no('page',($page-1)),'&url_page').$where_s.'" >上一页</a>&nbsp;';
	 for ($i; $i <= $j; $i++) {		
  
		 $str .= ($page == $i) ? '<span style="color:#FF0000;font-weight:bold">'.$i.'</span>&nbsp;' : '<a href="?'.get_explode(get_page_no('page',$i),'&url_page').$where_s.'">'.$i.'</a>&nbsp;';		    
	 }
	 $str .= ($page == $j) ? '' : '<a href="?'.get_explode(get_page_no('page',($page+1)),'&url_page').$where_s.'">下一页</a>&nbsp';

	 $str .= '&nbsp第 '.$page.' / '.$page_num.' 页';
	 $str .= '&nbsp&nbsp&nbsp<input id="go_page" type="text" size="4" />';
	 $str .= '<input type="button" value=" GO " onclick="var a = document.getElementById(\'go_page\').value;if( !a ){alert(\'请输入页码！\');return;}window.location.href=\'?'.get_explode(get_page_no('page',($page)),'&url_page').$where_s.'&page=\'+a;"/>';
	 return  $str;
}
   /**
 * 获得分页相关信息
 *
 * @access  public
 * @param   int     $sql        要进行分页的 上去 sql语句
 * @param   int     $pagesize   每页要显示多少条记录
 * @param   int     $page       页码
 * @return  mix
 */
function  get_page_info($sql,$pagesize,$page,$type = '')
{
	 $row_p = array();
   	 $start = 0;
	 $total = 0; //总数
	 if($type != 'count_union')
	 {
	  $row_p = $GLOBALS['db']->getOne($sql);
	
	  if(!empty($row_p))
	  {
	  	$total = $row_p;
	  }
	 }else 
	 {
	 	$query = $GLOBALS['db']->query($sql);
	 	$total = $GLOBALS['db']->num_rows($query);
	 }
     $page_num = ceil($total/$pagesize);
     if ($page_num < 1) {
	   $page_num = 1;
     } 
     if ($page > $page_num) {
	   $page = $page_num;
     }  

     $start = ($page - 1) * $pagesize;
     return array('start'=>$start,'page'=>$page,'total'=>$total,'page_num'=>$page_num);
}

/**
 * 得到不同网站的网站信息
 *
 * @param   $web_type    网站类型
 * @return  string       网站信息
 */
function get_web_info($web_type)
{
	switch ($web_type)
	{
		case 1://代表为wondershare网站
	  		return 'WS.COM';
	  	break;
	  	
	  	case 2://代表为aimersoft网站
	  		return 'Aimersoft';
	  	break;
	  	
	  	case 3://代表为anypdftools.com网站
	  		return 'Anypdftools';
	  	break;
	  	
	  	case 4://代表为applemacvideo.com网站
	  		return 'Applemacvideo';
	  	break;
	  	
	  	case 5://代表为www.wondershare.jp网站
	  		return 'Wondershare.JP';
	  	break;
	  	
	  	case 6://代表为www.wondershare.de网站
	 	 	return 'Wondershare.DE';
	  	break;
	  	
	  	case 7://代表为www.Spotmau.com网站
	  		return 'Spotmau';
	  	break;
	  	
	  	case 8://代表为www.Iskysoft.com网站
	  		return 'Iskysoft';
	  	break;
	  	
		case 11://代表为Wondershare.FR网站
	  		return 'Wondershare.FR';
	  	break;
	  	
		case 12://代表为Wondershare.ES网站
	  		return 'Wondershare.ES';
	  	break;
	  	
		case 13://代表为Wondershare.com.MX网站
	  		return 'Wondershare.com.MX';
	  	break;
	  	
		case 14://代表为Wondershare.com.BR网站
	  		return 'Wondershare.com.BR';
	  	break;
	  	
	  	case 15://代表为Daniusoft.com网站
	  		return 'Daniusoft.com';
	  		
	  	case 200 :		//----------------------------------------------- pkjueying
	  		return 'iskysoft.jp' ; 
	  	break;
	}
	
}

/**************************************
* 发布相关联的模板文件
* @param  string  $tmp_table     模板表数字Table_23 中的23
* @param  int     $tem_id        模板与基础数据关联的ID
* @param string   $tem_field     基础数据的ID字段对应在模板的字段
* @return int  0为发布木有成功，1为发布成功
**************************************/  
function pub_template($tmp_number = 0, $tem_id = '', $tem_field = '', $type = 'pub')
 {
   	   global $db;
	   if( !empty($tem_id) && !empty($tmp_number) && !empty($tem_field) )
	   {
			
			////更新修改时间以及修改人
			$sql = "UPDATE Table_{$tmp_number} SET MenderID = '{$_SESSION['AID']}', MendTime = {$_SERVER['REQUEST_TIME']} 
					WHERE FIND_IN_SET({$tem_field}, '{$tem_id}' ) ";

			$affect =  $GLOBALS['db']->query( $sql );
			
			if ($type == 'pub') {
				
				$sql = "SELECT D_ID, url FROM  Table_{$tmp_number} WHERE FIND_IN_SET({$tem_field}, '{$tem_id}' ) ";
				
				$result = $db->query($sql);

				while ($row = $db->fetch_array($result)) {
					
					
					 echo '<script type="text/javascript" 
					 src="http://cms.wondershare.com/bin/docList_'.$tmp_number.'.php?doPost=true&ID[]='.$row['D_ID'].'&action=pub"></script>';
			
				}
			
			}
					
			 return 1;
	   }
	    return 0;
}
	   
/**
 * 上传图片
 *
 * @param   string      $destination_folder     要上传到那个文件夹
 * @param   string      $_FILES     文件对象
 *
 * @return  string    文件名称
 */
function upload_image($destination_folder,$_FILES)
{
   	$uptypes=array('image/jpg', //上传文件类型列表
	'image/jpeg',
	'image/png',
	'image/pjpeg',
	'image/gif',
	'image/bmp',
	'image/x-png');
	 $max_file_size=5000000; //上传文件大小限制, 单位BYTE
    if (!is_uploaded_file($_FILES[tmp_name]))
	//是否存在文件
	{
		echo "<font color='red'>文件不存在！</font>";
		exit;
	}
    $file = $_FILES;
	if($max_file_size < $file["size"])
	//检查文件大小
	{
	echo "<font color='red'>文件太大！</font>";
	exit;
	}
    if(!in_array($file["type"], $uptypes))
	//检查文件类型
	{
	echo "<font color='red'>只能上传图像文件或Flash！</font>";
	exit;
	}
    if(!file_exists($destination_folder))
	mkdir($destination_folder);

	$filename=$file["tmp_name"];
	$image_size = getimagesize($filename);
	$pinfo=pathinfo($file["name"]);
	$ftype=$pinfo[extension];
	
	$destination = $destination_folder.time().".".$ftype;
	if (file_exists($destination) && $overwrite != true)
	{
	echo "<font color='red'>同名文件已经存在了！</a>";
	exit;
	}

	if(!move_uploaded_file ($filename, $destination))
	{	
	echo "<font color='red'>移动文件出错！</a>";
	exit;
	}
   $pinfo=pathinfo($destination);
   $fname=$pinfo[basename];
   return $fname;
}
   /**
 * 删除文件夹及其文件夹下所有文件
 *
 * @param   string      $dir     文件目录
 * @return  string  
 */
function delDirAndFile( $dirName )
{
	if ( $handle = opendir( "$dirName" ) ) 
	{
	   while ( false !== ( $item = readdir( $handle ) ) ) 
	   {
		   if ( $item != "." && $item != ".." ) 
		   {
			   if ( is_dir( "$dirName/$item" ) ) 
			   {
			  	 delDirAndFile( "$dirName/$item" );
			   } else 
			   {
			   		unlink( "$dirName/$item" );
			   }
		   }
	   }
	   closedir( $handle );
	   if( rmdir( $dirName ) )
	   return true;
	   else
	   return false;
	}
}


//循环创建文件夹
function brandToWebtype($brand)
{
	switch (strtolower($brand))
	{
		case 'wondershare'://代表为Wondershare品牌
	  		return 1;
	  	break;
	  	
	  	case 'aimersoft'://代表为Aimersoft品牌
	  		return 2;
	  	break;
	  	
	  	case 'anypdftools'://代表为anypdftools品牌
	  		return 3;
	  	break;
	  	
	  	case 'applemacvideo'://代表为applemacvideo品牌
	  		return 4;
	  	break;

	  	case 'spotmau'://代表为Spotmau品牌
	  		return 7;
	  	break;
	  	
	  	case 'iskysoft'://代表为Iskysoft品牌
	  		return 8;
	  	break;
		
	  	break;
	}
}

function MakeDir1($dirurl)
{
	$dir = split('[\/\\]',$dirurl);
	$strDir = "";
	for($i = 0; $i < count($dir); $i++)
	{
		$strDir .= $dir[$i]."/";
		if($strDir != "/")
		{
			if(!@is_dir($strDir))
			{
				@mkdir($strDir,0775);
				@chmod($strDir,0775);
			}
		}
	}
}
	
/**************************************
 * 插入记录
 * @param $file_dir   cdn同步要发布的文件夹，
 * @param $url   要写入cdn同步文件的url
 * @return string
 **************************************/   
function  cdnInsertFile($file_dir, $url) {
	
	$cdn_file = $file_dir.'/urls.txt';
	
	if (!is_dir($file_dir)) {
		MakeDir1($file_dir);
	}
	
	$url = $url."\n";
	
	if (file_exists($cdn_file)) {
		
		$contents = file_get_contents($cdn_file);
		//判断url是否存在文件中
		if (substr_count($contents, $url) == 0) {
			file_put_contents($cdn_file, $url, FILE_APPEND);
		}
		
	} else {
		file_put_contents($cdn_file, $url, FILE_APPEND);
	}
	
}


//发出提示
function alert($message = "", $action = "back", $location = "", $is_alert = true)
{
	global $time_start;
	
	
	$message .= '-----mysql:c|q&php:t'.(microtime(1) - $time_start) .'s';

	$path = dirname(__FILE__);
	$file_foot = $path."/foot.php";
	
	if($is_alert)
	{
		echo "$message <script>alert(\"$message\");</script>";
	}
	if($action == "location" && $location != '')
	{
		echo "<a href='$location' onclick='location.href=\"$location\";'>返回</a>";
		if($is_alert)
		{
			echo "<script>location.href='$location';</script>";
		}
		include($file_foot);
		exit;
	}
	if($action == "halt")
	{
		include($file_foot);
		exit;
	}
	if($action == "back")
	{
		echo "<a href='".$_SERVER['HTTP_REFERER']."' onclick='history.go(-1);'>返回</a>";
		if($is_alert)
		{
			echo "<script>history.go(-1);</script>";
		}
		include($file_foot);
		exit;
	}
}
?>